<template>
  <view class="create-order-page">
    <scroll-view class="scroll-content" :scroll-y="true">
      <!-- 地址选择 -->
      <view class="card address-card" @click="selectAddress">
        <view class="icon-wrapper">
          <uni-icons type="location-filled" size="20" color="#4A90E2"></uni-icons>
        </view>
        <view class="address-info-wrapper" v-if="selectedAddress.id">
          <view class="user-info">
            <text>{{ selectedAddress.name }}</text>
            <text class="phone">{{ selectedAddress.phone }}</text>
          </view>
          <view class="address-details">{{ selectedAddress.fullAddress }}</view>
        </view>
        <view class="no-address" v-else>请选择服务地址</view>
        <uni-icons class="arrow" type="right" size="18" color="#bbb"></uni-icons>
      </view>

      <!-- 服务信息 -->
      <view class="card service-info-card">
        <image class="service-image" :src="serviceInfo.image" mode="aspectFill"></image>
        <view class="service-details">
          <view class="title">{{ serviceInfo.title }}</view>
          <view class="subtitle">{{ serviceInfo.subtitle }}</view>
          <view class="price">¥{{ serviceInfo.price }} /{{ serviceInfo.unit }}</view>
        </view>
      </view>

      <!-- 备注、时间等选项 -->
      <view class="card options-list">
        <!-- [修改] 服务时间改为 picker 选择器 -->
        <picker mode="multiSelector" :range="timeRange" :value="selectedTimeIndex" @change="onTimeChange">
            <view class="option-item">
              <text class="label">服务时间</text>
              <view class="value-with-arrow">
                <text class="value" :class="{'placeholder': selectedTimeText === '请选择时间'}">{{ selectedTimeText }}</text>
                <uni-icons type="right" size="16" color="#bbb"></uni-icons>
              </view>
            </view>
          </picker>
        <view class="option-item">
          <text class="label">订单备注</text>
          <input class="remark-input" type="text" v-model="remark" placeholder="可填写特殊要求" placeholder-style="color:#bbb;"/>
        </view>
      </view>
    </scroll-view>

    <!-- [修改] 底部固定操作栏样式 -->
    <view class="sticky-footer" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <view class="total-price">
        <text class="label">订金：</text>
        <text class="amount">¥{{ deposit.toFixed(2) }}</text>
      </view>
      <button class="submit-btn" @click="submitOrder">提交订单</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { useSystemInfo } from '@/composables/useSystemInfo';
import { request } from '@/utils/request.js';
import { BASE_URL, DEPOSIT_AMOUNT } from '@/utils/config.js';
// [新增] 导入全局 store
import store from '@/utils/store.js';

const { safeAreaInsets } = useSystemInfo();

// ---- 响应式状态 ----
const serviceInfo = reactive({ id: null, title: '', image: '', price: '0', unit: '' });
const selectedAddress = reactive({ id: null, name: '', phone: '', fullAddress: '' });
const remark = ref('');
const deposit = ref(20.00);

// 时间选择器相关状态
const { timeRange, generateTimeSlots } = useTimePicker();
const selectedTimeIndex = ref([0, 0]);

// ---- 计算属性 ----
const selectedTimeText = computed(() => {
    if(!timeRange.value[0]?.length || !timeRange.value[1]?.length) return '请选择时间';
    const date = timeRange.value[0][selectedTimeIndex.value[0]];
    const time = timeRange.value[1][selectedTimeIndex.value[1]];
    if(!date || !time) return '请选择时间';
    return `${date} ${time}`;
});


// ---- API & 事件处理 ----
const loadPageData = async (serviceId) => {
  if (!serviceId) return;
  await Promise.all([
    fetchServiceDetailForOrder(serviceId),
    fetchDefaultAddress()
  ]);
};

const fetchServiceDetailForOrder = async (serviceId) => {
  try {
    const data = await request({
      url: `/servicesdetail`, // [修改] 新的URL
      method: 'POST',
      data: { serviceId: serviceId } // [修改] 参数在请求体中
    });
    serviceInfo.id = data.serviceId;
    serviceInfo.title = data.serviceMainName;
    serviceInfo.image = `${BASE_URL}${data.serviceHeadImg}`;
    serviceInfo.price = data.serviceMoney.toFixed(2);
    // unit 字段缺失
    serviceInfo.unit = "次";
  } catch (error) {
    console.error("加载服务信息失败:", error);
  }
};

const fetchDefaultAddress = async () => {
  try {
    const userId = uni.getStorageSync('userId');
    const data = await request({ url: '/my/addresses', method: 'POST', data: { userId } });
    const validAddresses = data.filter(addr => addr.addressIsExist !== 0);
    if (validAddresses.length > 0) {
      const defaultAddr = validAddresses[0];
      selectedAddress.id = defaultAddr.addressId;
      selectedAddress.name = defaultAddr.addressLinkman;
      selectedAddress.phone = defaultAddr.addressPhone;
      selectedAddress.fullAddress = `${defaultAddr.addressArea} ${defaultAddr.addressDetail}`;
    } else {
      Object.assign(selectedAddress, { id: null, name: '', phone: '', fullAddress: '' });
    }
  } catch (error) {
    console.error("加载默认地址失败:", error);
  }
};

const onTimeChange = (e) => {
    selectedTimeIndex.value = e.detail.value;
};

const selectAddress = () => uni.navigateTo({ url: '/pages/user/address-manage' });

const submitOrder = async () => {
  if (!selectedAddress.id) {
    return uni.showToast({ title: '请选择服务地址', icon: 'none' });
  }
  if (selectedTimeText.value === '请选择时间') {
    return uni.showToast({ title: '请选择服务时间', icon: 'none' });
  }

  // [核心] 拼接备注和服务时间
  const finalRemark = `【预约时间: ${selectedTimeText.value}】 ${remark.value}`.trim();

  const userId = uni.getStorageSync('userId');
  const params = {
    userId: userId,
    serviceId: serviceInfo.id,
    addressId: selectedAddress.id,
		orderStartMoney: DEPOSIT_AMOUNT,
		orderEndMoney: serviceInfo.price - DEPOSIT_AMOUNT,
    orderRemark: finalRemark, // 使用拼接后的备注
  };

  try {
    uni.showLoading({ title: '正在提交...' });
    const result = await request({
      url: '/addOrders',
      method: 'POST',
      data: params
    });
    
    uni.hideLoading();
    if (!result || !result.orderId) {
        throw new Error('后端未返回有效的订单ID');
    }
    const newOrderId = result.orderId;
    
    uni.redirectTo({
      url: `/pages/order-payment/order-payment?orderId=${newOrderId}`
    });
  } catch (error) {
    uni.hideLoading();
    console.error("创建订单失败:", error);
  }
};


// ---- 生命周期钩子 ----
onLoad((options) => {
  const serviceId = options.serviceId;
  if (serviceId) {
    loadPageData(serviceId);
    generateTimeSlots();
  } else {
    uni.showToast({title: '服务信息错误', icon: 'error'});
    setTimeout(() => uni.navigateBack(), 2500);
  }
});

// [核心修改] onShow 生命周期钩子
onShow(() => {
  // 检查全局 store 中是否有新选择的地址
  if (store.selectedAddress) {
    console.log('从 store 中检测到新地址，正在更新...');
    // 如果有，则使用它来更新当前页面的地址信息
    const newAddr = store.selectedAddress;
    selectedAddress.id = newAddr.id;
    selectedAddress.name = newAddr.name;
    selectedAddress.phone = newAddr.phone;
    selectedAddress.fullAddress = newAddr.fullAddress;
    
    // [关键] 使用完毕后，必须清空 store，以免下次返回时重复使用
    store.selectedAddress = null;
  } else {
    // 如果 store 中没有新地址（意味着是第一次加载或用户按物理键返回），
    // 并且当前页面还没有地址，则加载默认地址
    if (!selectedAddress.id) {
        console.log("Store中无新地址，加载默认地址");
        fetchDefaultAddress();
    }
  }
});


// ---- 工具函数 ----
function useTimePicker() {
    const timeRange = ref([[], []]);
    const generateTimeSlots = () => {
        const dates = [];
        const times = ['09:00-11:00', '11:00-13:00', '13:00-15:00', '15:00-17:00', '17:00-19:00'];
        const today = new Date();
        const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        for (let i = 0; i < 7; i++) {
            const date = new Date(today);
            date.setDate(today.getDate() + i);
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const dayOfWeek = week[date.getDay()];
            let label = `${month}月${day}日 ${dayOfWeek}`;
            dates.push(label);
        }
        timeRange.value = [dates, times];
    };
    return { timeRange, generateTimeSlots };
}
</script>

<style lang="scss" scoped>
.create-order-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $uni-bg-color;
}

.scroll-content {
  flex: 1;
  padding-bottom: 180rpx;
}

.card {
  background: $uni-bg-color-white;
  border-radius: 24rpx;
  margin: 30rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);
}

.address-card {
  display: flex;
  align-items: center;
  gap: 30rpx;
  
  .icon-wrapper {
    width: 64rpx;
    height: 64rpx;
    background-color: $uni-primary-light;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;
  }
  
  .address-info-wrapper { flex-grow: 1; }
  .user-info {
    font-size: 32rpx;
    font-weight: 500;
    margin-bottom: 10rpx;
    .phone { margin-left: 20rpx; color: $uni-text-color-light; font-weight: 400; }
  }
  .address-details { font-size: 28rpx; color: $uni-text-color-light; line-height: 1.5; }
  .no-address { flex-grow: 1; color: $uni-text-color-light; font-size: 32rpx; }
  .arrow { flex-shrink: 0; }
}

.service-info-card {
  display: flex;
  gap: 30rpx;
  
  .service-image { width: 160rpx; height: 160rpx; border-radius: 16rpx; flex-shrink: 0; }
  .service-details {
    flex-grow: 1;
    .title { font-size: 32rpx; font-weight: 500; margin-bottom: 16rpx; }
    .subtitle { font-size: 26rpx; color: $uni-text-color-light; margin-bottom: 20rpx; }
    .price { font-size: 32rpx; font-weight: bold; color: $uni-primary; }
  }
}

.options-list {
  padding: 0;
  .option-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 110rpx; // 保证点击区域
    padding: 0 40rpx;
    border-bottom: 1px solid $uni-bg-color;
    &:last-child { border-bottom: none; }
    .label { font-size: 30rpx; }
    .value { font-size: 30rpx; color: $uni-text-color-light; }
    .remark-input { width: 60%; text-align: right; font-size: 30rpx; color: $uni-text-color; }
  }
}

// [新增] 用于 picker 内部的 value 和箭头的组合
.value-with-arrow {
  display: flex;
  align-items: center;
  gap: 10rpx;
  .placeholder {
    color: #bbb; // 未选择时显示占位符颜色
  }
}

// [修改] 底部样式
.sticky-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $uni-bg-color-white;
  padding: 20rpx 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.08);
  display: flex;
  align-items: center; // 垂直居中
  justify-content: space-between; // 两端对齐
  
  .total-price {
    // flex-grow: 1; // 移除，让其内容自然宽度
  }
  .label { font-size: 28rpx; color: $uni-text-color-light; }
  .amount { font-size: 40rpx; font-weight: bold; color: $uni-primary; }

  .submit-btn {
    padding: 0 60rpx;
    height: 88rpx;
    line-height: 88rpx;
    background: linear-gradient(135deg, $uni-primary, $uni-accent);
    color: white;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    // 重置uniapp按钮默认样式
    margin: 0;
  }
}
</style>